package yxk.list.odc.homs.util;

import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import yxk.utils.BosUtil;
import yxk.utils.HttpRequestUtil;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

/*
 *
 *是否入职
 *@author lqh
 *@date 2023/9/21
 *
 */
public class OnboardUtil {

    private static final Log LOG = LogFactory.getLog(OnboardUtil.class);
    private DynamicObject writeBack;

    public DynamicObject getWriteBack() {
        if(writeBack == null){
            writeBack = BosUtil.getConfigUration("ZHAOPIN_HUIXIE");
        }
        return writeBack;
    }

    /**
     * 招聘获取token
     */
    public String getZhaoPinToken() {
        String result = "";
        DynamicObject url = getWriteBack();
        LOG.info("PunchcardDataUtil.getFSToken.config:{}", url);
        String nwg5Tokenurl = url.getString("nwg5_tokenurl");
        JSONObject param = new JSONObject();
        param.put("clientID", url.getString("nwg5_user"));
        param.put("clientSecret", url.getString("nwg5_password"));
        param.put("grantType", "client_credentials");
        LOG.info("PunchcardDataUtil.getFSToken.param:{}", param);
        try {
            String results = HttpRequestUtil.getPostResult(nwg5Tokenurl,null,param.toString(),"application/json;charset=utf-8");
            LOG.info("PunchcardDataUtil.getFSToken.result:{}", results);

            Map<String, Object> datas = JSONObject.parseObject(results);
            Object code = datas.get("code");
            if (code != null && code.equals(0)) {
                result = (String) ((Map) datas.get("data")).get("accessToken");
                return result;
            }

        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("RequesUtil.getFSToken.e:{}", e);
        }
        return result;
    }

    /**
     * 回写_候选人入职
     *
     * @param token           token
     * @param candidateNumber 候选人编号
     * @param probation       试用期
     * @param effectdate      入职时间
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public Map<String, Object> getHired(String token, String candidateNumber, Integer probation, Date effectdate) {
        DynamicObject url = getWriteBack();
         // 构建URL
        String nwg5Url = url.getString("nwg5_url");
        String nwg5_url = String.format(nwg5Url+"%s/hired", candidateNumber);
        LOG.info("OnboardUtil.getHired.candidateNumber:{}", candidateNumber);
        JSONObject param = new JSONObject();
        param.put("hiredAt", formatDate(new Date()));
        param.put("probation", probation);
        Map<String,String> map=new HashMap<>();
        map.put("Authorization", "Bearer " + token);
        LOG.info("OnboardUtil.getHired.param:{}", param);
        try {
            String results = HttpRequestUtil.getPutResult(nwg5_url,map,param.toString(),"application/json");
            LOG.info("OnboardUtil.getHired.result:{}", results);

            Map<String, Object> datas = JSONObject.parseObject(results);
            return datas;

        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("RequesUtil.getFSToken.e:{}", e);
        }
        return null;
    }

    /**
     * 回写_候选人未入职
     *
     * @param token           token
     * @param candidateNumber 候选人编号
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public Map<String, Object> getRejected(String token, String candidateNumber) {
        DynamicObject url = getWriteBack();
        // 构建URL
        String nwg5Url = url.getString("nwg5_url");
        String nwg5_url = String.format(nwg5Url+"%s/rejected", candidateNumber);
        JSONObject param = new JSONObject();
        //param.put("hiredAt", formatDate(new Date()));
        Map<String,String> map=new HashMap<>();
        map.put("Authorization","Bearer " + token);
        try {
            String results = HttpRequestUtil.getPutResult(nwg5_url,map,param.toString(),"application/json");
            LOG.info("PunchcardDataUtil.getFSToken.result:{}", results);

            Map<String, Object> datas = JSONObject.parseObject(results);
            return datas;

        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("RequesUtil.getFSToken.e:{}", e);
        }
        return null;
    }

    /**
     * 转正
     * @param toKen
     * @param param
     * @param candidatenumber  候选人编码
     * @return
     */
    public Boolean getCorrected(String toKen,String param,String candidatenumber) {
        // 构建URL
        DynamicObject url = getWriteBack();
        String nwg5_url = String.format(url+"%s/corrected", candidatenumber);
/*        param.put("status", map.get("status"));

        param.put("correctedAt", map.get("correctedAt") == null ? formatDateNow() : map.get("correctedAt"))*/;
        Map header=new HashMap<>();
        header.put("Authorization", "Bearer " + toKen);
        LOG.info("PunchcardDataUtil.getFSToken.param:{}", param);
        LOG.info("PunchcardDataUtil.getFSToken.nwg5_url:{}", nwg5_url);
        try {
            String results = HttpRequestUtil.getPutResult(nwg5_url,header,param.toString(),"application/json");
            LOG.info("PunchcardDataUtil.getFSToken.result:{}", results);
            JSONObject datas = JSONObject.parseObject(results);
            Boolean success = datas.getBoolean("success");
            return success;
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("RequesUtil.getFSToken.e:{}", e);
        }
        return null;
    }

    public static String formatDateNow() {
        // 设置时区为北京
        ZoneId beijingZone = ZoneId.of("Asia/Shanghai");

        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now(beijingZone);

        // 创建日期时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

        // 格式化时间为ISO 8601字符串
        String formattedDate = formatter.format(currentTime);

        return formattedDate;
    }

    /**
     * 回写_候选人离职
     *
     * @return {@link Map}<{@link String},{@link Object}>
     */
    public Map<String, Object> getResign(String token,String param,String number) {
        DynamicObject url = getWriteBack();
        // 构建URL
        String nwg5_url = String.format(url+"%s/resign", number);

        LOG.info("PunchcardDataUtil.getFSToken.param:{}", param);
        Map header=new HashMap<>();
        header.put("Authorization", "Bearer " + token);
        try {
            String results = HttpRequestUtil.getPutResult(nwg5_url,header,param.toString(),"application/json");
            LOG.info("PunchcardDataUtil.getFSToken.result:{}", results);

            Map<String, Object> datas = JSONObject.parseObject(results);

            return datas;

        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("RequesUtil.getFSToken.e:{}", e);
        }
        return null;
    }

    /**
     * 数据校验
     *
     * @param map
     * @param param
     * @return boolean
     */
    private static boolean ValidationData(Map<String, Object> map, JSONObject param) {
        /*if (map.get("reasonType") != null && "" != map.get("reasonType")) {
            param.put("reasonType", map.get("reasonType"));
        }*/

        if (map.get("detail") != null && "" != map.get("detail")) {
            param.put("detail", map.get("detail"));
        } else {
            return false;
        }

        /*if (map.get("time") != null && "" != map.get("time")) {
            param.put("time", map.get("time"));
        }

        if (map.get("email") != null && "" != map.get("email")) {
            param.put("email", map.get("email"));
        }

        if (map.get("talentPoolId") != null && "" != map.get("talentPoolId")) {
            param.put("talentPoolId", map.get("talentPoolId"));
        }

        if (map.get("isResignWriteJob") != null && "" != map.get("isResignWriteJob")) {
            param.put("isResignWriteJob", map.get("isResignWriteJob"));
        }

        if (map.get("resignJobName") != null && "" != map.get("resignJobName")) {
            param.put("resignJobName", map.get("resignJobName"));
        }

        if (map.get("resignDepartment") != null && "" != map.get("resignDepartment")) {
            param.put("resignDepartment", map.get("resignDepartment"));
        }

        if (map.get("reason") != null && "" != map.get("reason")) {
            param.put("reason", map.get("reason"));
        }

        if (map.get("resignJobType") != null && "" != map.get("resignJobType")) {
            param.put("resignJobType", map.get("resignJobType"));
        }*/
        return true;
    }


    public static String formatDate(Date date) {
        // 设置时区为北京
        TimeZone beijingTimeZone = TimeZone.getTimeZone("Asia/Shanghai");

        // 创建一个SimpleDateFormat对象，用于指定输出格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

        // 设置时区
        sdf.setTimeZone(beijingTimeZone);

        // 格式化Date对象为ISO 8601日期时间字符串
        String formattedDate = sdf.format(date);
        return formattedDate;
    }
}
